import { defineStore } from 'pinia'
import { ref } from 'vue'

/**
 * 用户状态管理
 * @author Logan.Li
 */
export const useUserStore = defineStore('user', () => {
  const userInfo = ref({
    username: '',
    role: '管理员',
    avatar: '',
    email: ''
  })

  const token = ref('')
  const isLoggedIn = ref(false)

  // 检查token是否过期
  const isTokenExpired = () => {
    const expirationTime = localStorage.getItem('tokenExpiration')
    if (!expirationTime) {
      return true // 没有过期时间，认为已过期
    }
    return Date.now() > parseInt(expirationTime)
  }

  // 初始化用户信息
  const initUserInfo = () => {
    const storedToken = localStorage.getItem('token')
    const storedUsername = localStorage.getItem('username')
    const storedUserInfo = localStorage.getItem('userInfo')
    
    console.log('initUserInfo检查:', { storedToken: !!storedToken, storedUsername, storedUserInfo: !!storedUserInfo })
    
    // 检查token是否存在且未过期
    if (storedToken && !isTokenExpired()) {
      token.value = storedToken
      isLoggedIn.value = true
      
      // 优先使用完整的用户信息，否则使用用户名
      if (storedUserInfo) {
        try {
          userInfo.value = JSON.parse(storedUserInfo)
        } catch (error) {
          console.error('解析用户信息失败:', error)
          if (storedUsername) {
            userInfo.value.username = storedUsername
          }
        }
      } else if (storedUsername) {
        userInfo.value.username = storedUsername
      }
      console.log('用户信息初始化成功')
    } else {
      console.log('token不存在或已过期，清除用户信息')
      // token过期或不存在，清除所有信息
      clearUserInfo()
    }
  }

  // 设置用户信息
  const setUserInfo = (info) => {
    userInfo.value = { ...userInfo.value, ...info }
    // 持久化用户信息到localStorage
    localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
    if (info.username) {
      localStorage.setItem('username', info.username)
    }
  }

  // 设置token
  const setToken = (newToken) => {
    token.value = newToken
    // 设置token过期时间为一周
    const expirationTime = Date.now() + (7 * 24 * 60 * 60 * 1000) // 7天
    localStorage.setItem('token', newToken)
    localStorage.setItem('tokenExpiration', expirationTime.toString())
    isLoggedIn.value = true
  }

  // 清除用户信息
  const clearUserInfo = () => {
    userInfo.value = {
      username: '',
      role: '管理员',
      avatar: '',
      email: ''
    }
    token.value = ''
    isLoggedIn.value = false
    localStorage.removeItem('token')
    localStorage.removeItem('tokenExpiration')
    localStorage.removeItem('username')
    localStorage.removeItem('userInfo')
  }

  // 获取当前用户名
  const getCurrentUsername = () => {
    return userInfo.value.username || localStorage.getItem('username') || '未知用户'
  }

  // 用户登出
  const logout = async () => {
    try {
      // 清除本地存储的用户信息
      clearUserInfo()
      return Promise.resolve()
    } catch (error) {
      console.error('登出失败:', error)
      return Promise.reject(error)
    }
  }

  return {
    userInfo,
    token,
    isLoggedIn,
    initUserInfo,
    setUserInfo,
    setToken,
    clearUserInfo,
    getCurrentUsername,
    logout,
    isTokenExpired
  }
})
